package com.bins.smartdoc.controller;

import com.bins.smartdoc.common.response.ResultBody;
import com.bins.smartdoc.model.User;
import com.bins.smartdoc.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 用户模块
 * @author Andybin
 * @date 20210926
 */

@Slf4j
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 添加用户
     * @param user 用户对象
     * @return
     */
    @PostMapping("/addUser")
    public ResultBody addUser(@RequestBody User user) {
        try {
            userService.addUser(user);
            return ResultBody.isOK();
        } catch (Exception e) {
            log.error("添加用户失败", e);
            return ResultBody.isFail();
        }
    }

    /**
     * 修改用户
     * @param user
     * @return
     */
    @PutMapping(value = "/updateUser")
    public ResultBody updateUser(@RequestBody User user) {
        try {
            userService.updateUser(user);
            return ResultBody.isOK();
        } catch (Exception e) {
            log.error("修改用户失败", e);
            return ResultBody.isFail();
        }
    }

    /**
     * 删除用户
     * @param id
     * @return
     */
    @DeleteMapping("/deleteUser/{id}")
    public ResultBody deleteUserById(@PathVariable(name = "id", required = true) Long id) {
        try {
            userService.deleteUser(id);
            return ResultBody.isOK();
        } catch (Exception e) {
            log.error("修改用户失败", e);
            return ResultBody.isFail();
        }
    }

    /**
     * 查询所有用户
     * @return
     */
    @GetMapping("/findAll")
    public ResultBody listUser() {
        try {
            List<User> list = userService.listUser();
            return ResultBody.isOK(list);
        } catch (Exception e) {
            log.error("查询所有用户失败", e);
            return ResultBody.isFail();
        }
    }

    /**
     * 根据Id查询用户
     * @param id
     * @return
     */
    @GetMapping("/findById/{id}")
    public ResultBody findById(@PathVariable(name = "id") Long id) {
        try {
            User user = userService.findById(id);
            return ResultBody.isOK(user);
        } catch (Exception e) {
            log.error("查询用户失败", e);
            return ResultBody.isFail();
        }
    }

}
